﻿using Models.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Models.Common.EnumDeviceState;
using Microsoft.EntityFrameworkCore;
using GatewayServerService.Mq;
using Models.Device;
using Newtonsoft.Json;
using UtilsBase;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using UtilsORM;
using UtilsORM.MySqlData;
using Models.Constant;
using GatewayServerService.CloudCenter;

namespace GatewayServerService.CloudCenter
{
    public class ServiceCloudGateWay_Init
    {

        /// <summary>
        /// 重置gpio状态  为低电平 状态
        /// </summary>
        /// <param name="model_GateWay"></param>
        public void resetGpioState(string dguid)
        {
            try
            {
                //判断是否高低电平引脚输出
                string sqldguid = "select a.d_guid from iot_device a inner join iot_device_model on d_model_guid=m_guid inner join iot_device_model_type on m_type_guid=t_guid where t_code='" + (int)EnumDeviceModelType.ModelType.gpio + "' and  d_gw_d_guid='" + dguid + "'";
                DataTable dt = new MySqlYihongIot().Db.Ado.GetDataTable(sqldguid);
                foreach (DataRow dr in dt.Rows)
                {
                    // new ServiceCloudDeviceLiveState().setDeviceLiveState(dr["d_guid"].ToString(), (int)Gpio_Live_State.close, "");
                    new ServiceCloudDeviceValueLog().writeSensorlog(dr["d_guid"].ToString(), "status", "close", "关闭");

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// 检查rs485继电器状态
        /// </summary>
        /// <param name="model_GateWay"></param>
        public void resetRS485RelayState(string dguid)
        {
            try
            {
                string sqldguid = "select a.d_guid from iot_device a inner join iot_device_model on d_model_guid=m_guid inner join iot_device_model_type on m_type_guid=t_guid where t_code='" + (int)EnumDeviceModelType.ModelType.Relay485 + "' and  d_gw_d_guid='" + dguid + "' order by d_id asc";
                DataTable dt = new MySqlYihongIot().Db.Ado.GetDataTable(sqldguid);
                foreach (DataRow dr in dt.Rows)
                {
                    new ServiceCloudDeviceCommand().sendCommandToGateWay(dr["d_guid"].ToString(), GpioCommandEnum.CHECK_STATE, "网关重启检查状态");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        EFYihongIotContext ef = new EFYihongIotContext();

        /// <summary>
        /// 重置设备状态，，设备运行时，callback再检测是否异常 
        /// </summary>
        /// <param name="model_GateWay"></param>
        public void resetDeviceLiveState(string dguid)
        {
            try
            {
                List<iot_device> devices = ef.iot_device.Where(c => c.d_gw_d_guid == dguid).ToList();
                foreach (iot_device device in devices)
                {
                    string sqlupd = "update iot_device_live_state set ls_live_state=1 where ls_live_state in(2,3) and ls_d_guid='" + device.d_guid + "'";
                    new MySqlYihongIot().Db.Ado.ExecuteCommand(sqlupd);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        /// <summary>
        /// 更新异常的设备状态
        /// </summary>
        /// <param name="model_GateWay"></param>
        public void resetDeviceErrorLiveState(string dguid)
        {
            int[] list = { 2, 3 };//要查询的数组列表
            try
            {
                List<iot_device_live_state> live_States = (from sl in ef.iot_device_live_state
                                                           join d in ef.iot_device on sl.ls_d_guid equals d.d_guid
                                                           where d.d_gw_d_guid == dguid && list.Contains(sl.ls_live_state)
                                                           select sl).ToList();

                foreach (iot_device_live_state live_State in live_States)
                {
                    iot_device_value_current current = ef.iot_device_value_current.Where(c => c.vc_d_guid == live_State.ls_d_guid && c.vc_add_time > live_State.ls_live_state_set_time).FirstOrDefault();
                    if (current != null)
                    {
                        string sqlupd = "update iot_device_live_state set ls_live_state=1 where  ls_guid='" + live_State.ls_guid + "'";
                        new MySqlYihongIot().Db.Ado.ExecuteCommand(sqlupd);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        /// <summary>
        /// 重启网关
        /// </summary>
        /// <param name="model_GateWay"></param>
        public void restartGateWay(ModelGateway model_GateWay)
        {
            try
            {
                if (model_GateWay.cpuTemperature > 70 && Convert.ToDateTime(model_GateWay.startTime) < DateTime.Now.AddHours(-1))
                {
                    string result = new ServiceCloodAPIControl_ext().sendBashCommand("reboot", model_GateWay.gatewayCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        /// <summary>
        /// 清理未完成的流程
        /// </summary>
        /// <param name="model_GateWay"></param>
        public void deletePlainItemHandle(string dguid)
        {
            try
            {
                List<iot_device> devices = ef.iot_device.Where(c => c.d_gw_d_guid == dguid).ToList();
                foreach (iot_device device in devices)
                {
                    iot_device_task_plain_item_handle handle = ef.iot_device_task_plain_item_handle.Where(c => c.tpi_taskobj_guid == device.d_guid).FirstOrDefault();
                    if (handle != null)
                    {
                        ef.iot_device_task_plain_item_handle.Where(c => c.tpi_tp_guid == handle.tpi_tp_guid).ExecuteDeleteAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        /// <summary>
        /// 清理未完成的触发内容
        /// </summary>
        /// <param name="model_GateWay"></param>
        public void deleteconditionItemHandle(string dguid)
        {
            try
            {
                List<iot_device> devices = ef.iot_device.Where(c => c.d_gw_d_guid == dguid).ToList();
                foreach (iot_device device in devices)
                {
                    iot_device_linkage_condition_handle handle = ef.iot_device_linkage_condition_handle.Where(c => c.lc_d_guid == device.d_guid).FirstOrDefault();
                    if (handle != null)
                    {
                        ef.iot_device_linkage_condition_handle.Where(c => c.lc_l_guid == handle.lc_l_guid).ExecuteDeleteAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        /// <summary>
        /// 发送测试报文到网关
        /// </summary>
        /// <param name="model_GateWay"></param>
        public void sendTest(string gatewayCode)
        {
            try
            {
                new ServiceSendMQ().sendCommand("发送测试，创建mq通道", gatewayCode, MQEventEnum.Device_Test);
                new ServiceSendMQ().sendCommand("发送测试，创建mq通道", gatewayCode, MQEventEnum.Device_Test, ConstantAppName.gateway_upgrade);
                // new ServiceSendMQ().sendCommand("发送测试，创建mq通道", model_GateWay.gatewayCode, MQEventEnum.MQServer_RemoteClientQueueName, MQEventEnum.Device_Test);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        public void sendTimeToGateWay(ModelGateway model_GateWay)
        {
            try
            {
                new ServiceSendMQ().sendCommand(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), model_GateWay.gatewayCode, MQEventEnum.Device_Gateway_Time);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}
